#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
请求拦截/重放/监听组件 Flask 应用工厂
"""

import os
import logging
from flask import Flask
from flask_cors import CORS
from intercept.api.routes.http_data import http_data_bp
from intercept.api.routes.intercept import intercept_bp
from intercept.api.routes.proxy import proxy_bp
from intercept.api.routes.intercept_control import intercept_control_bp
from intercept.api.routes.request_intercept import request_intercept_bp
from db.mongo import init_db

logger = logging.getLogger(__name__)

def create_app():
    """创建并配置 Flask 应用"""
    app = Flask(__name__)

    # 配置日志级别，去除健康检查日志
    import logging
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)  # 只显示 ERROR 及以上级别的日志

    # 配置 CORS
    CORS(app)

    # 配置应用
    app.config.from_mapping(
        SECRET_KEY=os.getenv('SECRET_KEY', 'dev'),
    )

    # 设置 MongoDB URI
    import urllib.parse
    username = urllib.parse.quote_plus(os.getenv('MONGO_USERNAME', 'root'))
    password = urllib.parse.quote_plus(os.getenv('MONGO_PASSWORD', 'Zmzzmz010627!'))
    host = os.getenv('MONGO_HOST', '116.63.51.45')
    port = os.getenv('MONGO_PORT', '27017')
    db_name = os.getenv('MONGO_DB', 'kube-replayer')
    app.config['MONGO_URI'] = f"mongodb://{username}:{password}@{host}:{port}/{db_name}"

    # 初始化数据库
    init_db(app)

    # 注册蓝图
    app.register_blueprint(http_data_bp, url_prefix='/api/http_data')
    app.register_blueprint(intercept_bp, url_prefix='/api/intercept')
    app.register_blueprint(proxy_bp, url_prefix='/api/proxy')
    app.register_blueprint(intercept_control_bp, url_prefix='/api/intercept_control')
    app.register_blueprint(request_intercept_bp, url_prefix='/api/request/intercept')

    # 注册错误处理器
    @app.errorhandler(404)
    def not_found(error):
        return {'error': 'Not found'}, 404

    @app.errorhandler(500)
    def server_error(error):
        logger.error(f"服务器错误: {error}")
        return {'error': 'Internal server error'}, 500

    # 健康检查端点
    @app.route('/health')
    def health_check():
        return {'status': 'ok'}

    return app
